package org.xtetris;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;

public class Device extends Canvas implements Constants{
	protected int fullScreenWidth, fullScreenHeight, halfFullScreenWidth,
			halfFullScreenHeight;

	protected int lastKeyPressed;
	protected long keyPressedTime;
	protected int keyPressed;
	
	protected int repeatedKey = -1;
	protected void keyPressed(int keyCode) {
		keyPressedTime = System.currentTimeMillis();
		int abstractKeyCode = getAbstractKeyCode(keyCode);
		lastKeyPressed |= abstractKeyCode;
		keyPressed |= abstractKeyCode;
	}

	protected void keyReleased(int keyCode) {
		int abstractKeyCode = getAbstractKeyCode(keyCode);
		keyPressed &= ~abstractKeyCode;
		
		if(repeatedKey != 0){
			if(repeatedKey == abstractKeyCode){
				keyPressedTime = 0;
				repeatedKey = -1;				
			}
		}
	}

	protected boolean isKeyPressed(int abstractKey) {
		boolean pressed = (keyPressed & abstractKey) != 0;
		
		if(pressed){
			keyPressed &= ~abstractKey;
		}
		return pressed;
	}

	protected void paint(Graphics g) {
		
	}

	protected int getAbstractKeyCode(int keyCode) {
		switch (keyCode) {
		case Canvas.KEY_NUM0:
			return KEY_0;
		case Canvas.KEY_NUM2:
			return KEY_UP;
		case Canvas.KEY_NUM4:
			return KEY_LEFT;
		case Canvas.KEY_NUM6:
			return KEY_RIGHT;
		case Canvas.KEY_NUM8:
			return KEY_DOWN;
		case Canvas.KEY_NUM1:
			return KEY_1;
		case Canvas.KEY_NUM3:
			return KEY_3;
		case Canvas.KEY_NUM7:
			return KEY_7;
		case Canvas.KEY_NUM9:
			return KEY_9;
		case Canvas.KEY_NUM5:
			return KEY_FIRE;
		case Canvas.KEY_POUND:
			return Constants.KEY_POUND;
		case Canvas.KEY_STAR:
			return Constants.KEY_STAR;
		case -6:
			return Constants.KEY_LEFT_SOFT;
		case -7:
			return Constants.KEY_RIGHT_SOFT;
		}
		
		try {
			int actionCode = getGameAction(keyCode);
			switch (actionCode) {
			case Canvas.LEFT:
				return KEY_LEFT;
			case Canvas.RIGHT:
				return KEY_RIGHT;
			case Canvas.UP:
				return KEY_UP;
			case Canvas.DOWN:
				return KEY_DOWN;
			}
		} catch (Exception e) {
			System.out.println("exception happens when game game action");
		}
		
		return KEY_NONE;
	}

}
